const {
	db,
	dbCmd,
	$,
	result_success,
	result_error,
	appletInfoCollection,
	shopieCollection,
	userCollection
} = require('../../common/constants')
module.exports = async function(params = {}) {
	const token = this.getUniIdToken()
	if (!token) {
		return result_error('登录失效,请重新登录')
	}
	let payload = await this.uniID.checkToken(token)
	if (payload.code) {
		return payload
	}
	let cUser = await userCollection.doc(payload.uid).get()
	cUser = cUser.data[0]
	if(!cUser.app_id){
		return result_success({})
	}
	//获取当前应用
	let appletInfoData = await appletInfoCollection.doc(cUser.app_id).get()
	appletInfoData = appletInfoData.data[0]
	let cDate = new Date()
	if (cDate && cDate.toString().indexOf('UTC') > -1) {
		cDate.setHours(cDate.getHours() + 8)
	}
	let cYear = cDate.getFullYear();
	let cMonth = cDate.getMonth() + 1;
	let cDay = cDate.getDate();

	let sDate = cDate.setDate(cDate.getDate() - 30)
	sDate = new Date(sDate)

	let timezone = 8;
	let calDateTime = timezone * 60 * 60 * 1000;
	
	let queryShopieTotal = {
		app_id: appletInfoData._id,
		shop_id: appletInfoData._id,
		"cate": "商城订单",
		type: 0
	};

	let categories = []
	let seriesData = []
	let businessTotal = 0
	for (i = 0; i < 30; i++) {
		sDate = cDate.setDate(cDate.getDate() + 1)
		sDate = new Date(sDate)
		let sYear = sDate.getFullYear();
		let sMonth = sDate.getMonth() + 1;
		let sDay = sDate.getDate();
		let startDate = new Date(sYear + "-" + sMonth + "-" + sDay + ' 00:00:00');
		let endDate = new Date(sYear + "-" + sMonth + "-" + sDay + ' 23:59:59');
		let startDateTime;
		let endDateTime;
		if (startDate && startDate.toString().indexOf('UTC') > -1) {
			startDateTime = startDate.getTime() - calDateTime;
			endDateTime = endDate.getTime() - calDateTime;
		} else {
			startDateTime = startDate.getTime();
			endDateTime = endDate.getTime();
		}
		queryShopieTotal.create_time = dbCmd.gte(startDateTime).and(dbCmd.lte(endDateTime))
		if (params.type === 'count') {
			let businessCount = await shopieCollection.aggregate().match(queryShopieTotal).group({
				_id: '$_id'
			}).limit(1000).end();
			let business_count = businessCount.data.length
			if (business_count) {
				categories.push(sMonth + "-" + sDay)
				seriesData.push(business_count)
			}
		} else {
			businessTotal = await shopieCollection.aggregate().match(queryShopieTotal).group({
				_id: '$app_id',
				total: $.sum('$money')
			}).limit(1000).end();
			let business_total = 0
			if (businessTotal.data[0] && businessTotal.data[0].total) {
				business_total = (businessTotal.data[0].total / 100).toFixed(2)
			}
			if (business_total) {
				categories.push(sMonth + "-" + sDay)
				seriesData.push(business_total)
			}
		}

	}
	let rData = {
		"categories": categories,
		"series": [{
			"name": "",
			"data": seriesData
		}]
	}
	return result_success(rData)
}